/**
 * Dynamic Island测试模块
 */

import React, { useState, useEffect } from 'react';
import { Card, Button, Space, Typography, Alert, Input, Row, Col, Form } from 'antd';
import { PlayCircleOutlined, PauseCircleOutlined, StopOutlined, ReloadOutlined } from '@ant-design/icons';
import { useNotificationManager } from '../../../utils/notificationHelpers';
import { getStorageInfo, clearNotificationStorage } from '../../../utils/notificationStorage';
import { showNotification } from '../../../utils/notification';

const { Paragraph, Text } = Typography;

const DynamicIslandTests: React.FC = () => {
  const notificationManager = useNotificationManager();
  const [storageInfo, setStorageInfo] = useState(getStorageInfo());
  const [customTitle, setCustomTitle] = useState('');
  const [customDescription, setCustomDescription] = useState('');

  // 更新存储信息
  useEffect(() => {
    const interval = setInterval(() => {
      setStorageInfo(getStorageInfo());
    }, 1000);
    return () => clearInterval(interval);
  }, []);

  // 模拟数据库解析
  const simulateDatabaseParsing = () => {
    const parseId = notificationManager.createNotification({
      type: 'progress',
      title: '解析数据库',
      description: '正在分析表结构和关系',
      status: 'running',
      persistent: true,
      autoClose: false,
    });

    let progress = 0;
    const tables = ['users', 'orders', 'products', 'categories', 'reviews'];
    
    const interval = setInterval(() => {
      progress += 20;
      const currentTable = tables[Math.floor(progress / 20) - 1] || 'completed';
      
      notificationManager.updateProgress(
        parseId,
        progress,
        `解析表: ${currentTable}`,
        `${progress}% 完成`
      );
      
      if (progress >= 100) {
        clearInterval(interval);
        notificationManager.complete(parseId, true, '数据库解析完成', {
          tables: tables.length,
          relations: 12
        });
      }
    }, 1500);
  };

  // 模拟文件上传
  const simulateFileUpload = () => {
    const uploadId = notificationManager.createFileUpload('data_export.csv', 1024 * 1024 * 10);
    
    let progress = 0;
    const interval = setInterval(() => {
      progress += 12;
      notificationManager.updateProgress(
        uploadId,
        progress,
        `上传中 ${progress}%`,
        `${Math.round(10 * progress / 100 * 100) / 100} MB / 10 MB`
      );
      
      if (progress >= 100) {
        clearInterval(interval);
        notificationManager.complete(uploadId, true, '文件上传成功');
      }
    }, 800);
  };

  // 模拟数据同步
  const simulateDataSync = () => {
    const syncId = notificationManager.createDataSync('MySQL', 'Redis');
    
    let progress = 0;
    const steps = ['连接源数据库', '读取数据', '转换格式', '写入目标', '验证完整性'];
    
    const interval = setInterval(() => {
      progress += 20;
      const stepIndex = Math.floor(progress / 20) - 1;
      const currentStep = steps[stepIndex] || '完成';
      
      notificationManager.updateProgress(
        syncId,
        progress,
        currentStep,
        `步骤 ${Math.min(Math.floor(progress / 20), steps.length)}/${steps.length}`
      );
      
      if (progress >= 100) {
        clearInterval(interval);
        notificationManager.complete(syncId, true, '数据同步完成', {
          synced: 2500,
          errors: 0
        });
      }
    }, 1200);
  };

  // 模拟系统监控
  const simulateSystemMonitoring = () => {
    const monitorId = notificationManager.createNotification({
      type: 'monitoring',
      title: '系统监控',
      description: '监控系统性能指标',
      status: 'running',
      persistent: true,
      autoClose: false,
    });

    let counter = 0;
    const interval = setInterval(() => {
      counter++;
      const cpuUsage = Math.floor(Math.random() * 30) + 20;
      const memoryUsage = Math.floor(Math.random() * 40) + 30;
      
      notificationManager.updateProgress(
        monitorId,
        Math.min(counter * 2, 100),
        `CPU: ${cpuUsage}%, 内存: ${memoryUsage}%`,
        `运行时间: ${counter} 分钟`
      );
      
      if (counter >= 50) {
        clearInterval(interval);
        notificationManager.complete(monitorId, true, '监控完成');
      }
    }, 2000);
  };

  // 创建自定义通知
  const createCustomNotification = (persistent: boolean) => {
    if (!customTitle.trim()) return;
    
    if (persistent) {
      notificationManager.createNotification({
        type: 'task',
        title: customTitle,
        description: customDescription,
        status: 'running',
        persistent: true,
        autoClose: false,
      });
    } else {
      showNotification('info', customTitle, customDescription);
    }
  };

  // 清理存储
  const handleClearStorage = () => {
    clearNotificationStorage();
    notificationManager.clearAll();
    setStorageInfo(getStorageInfo());
    showNotification('success', '存储已清理', '所有持久化通知已删除');
  };

  // 刷新页面测试
  const handleRefreshTest = () => {
    if (storageInfo.notificationCount > 0) {
      window.location.reload();
    } else {
      showNotification('warning', '请先创建持久化通知', '创建一些通知后再测试页面刷新功能');
    }
  };

  return (
    <div>
      <Alert
        message="Dynamic Island说明"
        description="Dynamic Island是iOS风格的通知显示组件，专门用于显示进度通知和长时间运行的任务。它支持实时进度更新、用户交互控制和持久化存储。"
        type="info"
        showIcon
        style={{ marginBottom: 24 }}
      />

      {/* 预设通知测试 */}
      <Card title="预设通知测试" style={{ marginBottom: 16 }}>
        <Paragraph type="secondary">
          这些通知会显示在Header的Dynamic Island中，支持进度显示和交互控制：
        </Paragraph>
        
        <Row gutter={16}>
          <Col xs={24} sm={12} md={6}>
            <Button 
              icon={<PlayCircleOutlined />}
              onClick={simulateDatabaseParsing}
              block
              style={{ marginBottom: 8 }}
            >
              数据库解析
            </Button>
          </Col>
          <Col xs={24} sm={12} md={6}>
            <Button 
              icon={<PlayCircleOutlined />}
              onClick={simulateFileUpload}
              block
              style={{ marginBottom: 8 }}
            >
              文件上传
            </Button>
          </Col>
          <Col xs={24} sm={12} md={6}>
            <Button 
              icon={<PlayCircleOutlined />}
              onClick={simulateDataSync}
              block
              style={{ marginBottom: 8 }}
            >
              数据同步
            </Button>
          </Col>
          <Col xs={24} sm={12} md={6}>
            <Button 
              icon={<PlayCircleOutlined />}
              onClick={simulateSystemMonitoring}
              block
              style={{ marginBottom: 8 }}
            >
              系统监控
            </Button>
          </Col>
        </Row>
      </Card>

      {/* 自定义通知测试 */}
      <Card title="自定义通知测试" style={{ marginBottom: 16 }}>
        <Form layout="vertical">
          <Row gutter={16}>
            <Col xs={24} sm={12}>
              <Form.Item label="通知标题">
                <Input 
                  placeholder="输入通知标题" 
                  value={customTitle}
                  onChange={(e) => setCustomTitle(e.target.value)}
                />
              </Form.Item>
            </Col>
            <Col xs={24} sm={12}>
              <Form.Item label="通知描述">
                <Input 
                  placeholder="输入通知描述" 
                  value={customDescription}
                  onChange={(e) => setCustomDescription(e.target.value)}
                />
              </Form.Item>
            </Col>
          </Row>
          <Space>
            <Button 
              type="primary"
              onClick={() => createCustomNotification(true)}
              disabled={!customTitle.trim()}
            >
              创建持久通知
            </Button>
            <Button
              onClick={() => createCustomNotification(false)}
              disabled={!customTitle.trim()}
            >
              创建临时通知
            </Button>
          </Space>
        </Form>
      </Card>

      {/* 存储管理 */}
      <Card title="存储管理">
        <Row gutter={16} align="middle">
          <Col xs={24} sm={12}>
            <Space direction="vertical">
              <Text>
                <Text strong>存储状态：</Text>
                {storageInfo.hasStoredNotifications 
                  ? `已存储 ${storageInfo.notificationCount} 个通知` 
                  : '暂无存储的通知'
                }
              </Text>
              <Text type="secondary">
                存储大小：{Math.round(storageInfo.storageSize / 1024 * 100) / 100} KB
              </Text>
            </Space>
          </Col>
          <Col xs={24} sm={12}>
            <Space>
              <Button 
                icon={<ReloadOutlined />}
                onClick={handleRefreshTest}
              >
                刷新页面测试
              </Button>
              <Button 
                danger
                onClick={handleClearStorage}
              >
                清理存储
              </Button>
            </Space>
          </Col>
        </Row>
      </Card>
    </div>
  );
};

export default DynamicIslandTests;
